<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 手表套餐退款管理
 *
 * @icon fa fa-circle-o
 */
class Packagerefund extends Backend
{

    /**
     * Packagerefund模型对象
     * @var \app\admin\model\Packagerefund
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Packagerefund;
        $this->view->assign("stateList", $this->model->getStateList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['user','order'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','user_id','order_id','price','images','createtime','state']);
                $row->visible(['user']);
				$row->getRelation('user')->visible(['username']);
				$row->visible(['order']);
				$row->getRelation('order')->visible(['deviceid']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 退款详情 1.1.3升级
     */
    public function detail($ids = null)
    {
        $where = [];
        if($ids){
            $where['id'] = $ids;
        }
        $row = $this->model
            ->where($where)
            ->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $row['images'] = explode(',', $row['images']);
        $row['log'] = model('\app\admin\model\WatchPackageRefundLog')
            ->where(['refund_id' => $row['id']])
            ->order('createtime desc')
            ->select();
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 同意退款
     */
    public function agree($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($row['state'] == 2 || $row['state'] == 3 || $row['state'] == 4 || $row['state'] == 5) {
            $this->error(__('当前状态，不可操作'));
        }
        $error = '';
        Db::startTrans();
        try {
            // 判断退款类型 我要退款(无需退货)
            $refundType = 1;
            $refund_status = 2;
            $data['state'] = 1; // 先同意退款，还需要买家继续退货
            $data['agreetime'] = time(); // 卖家同意 时间
            // 退货地址
            $refundLog = '同意退货申请，退货地址：'.'浙江合念科技有限公司'.'，'.'13063679366'.'，'.'浙江省杭州市西湖区三墩镇数字信息产业园2期A座A421';
            if(!$error){
                // 只有本地余额退款状态4,和先同意退款,需要商家继续退款状态1执行,状态7原路返回在回调更新状态
                if($data['state'] == 1 || $data['state'] == 4){
                    // 1.0.5 更新商品状态
                    $this->setOrderState($refund_status, $row['order_id']);
                }
                // 写入日志
                $this->refundLog($row['user_id'], $ids, $refundLog, $refundType);
                // 更新退款
                $row->allowField(true)->save($data);
            }
            Db::commit();
        } catch (ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (!$error) {
            $this->success();
        } else {
            $this->error($error);
        }
    }

    /**
     * 确认收货
     */
    public function receiving($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($row['state'] == 2 || $row['state'] == 3 || $row['state'] == 4 || $row['state'] == 5) {
            $this->error(__('当前状态，不可操作'));
        }
        // 退款订单状态
        $state = 4;
        // 退款日志
        $refundLog = '平台确认收到退货，并将'.$row['price'].'元退款到买家账号余额';
        $refundType = 1;
        $result = false;
        Db::startTrans();
        try {
            // 判断业务类型
            $orderModel = model('\app\admin\model\package\Order');
            $order = $orderModel->get($row['order_id']);
            // 判断金额
            if($row['price'] > $order['payamount']){
                throw new Exception("非法退款金额，金额超过订单金额！！请拒绝退款！！");
            }
            // 1.1.5升级 第三方退款
            $config = get_addon_config('wanlshop');
            // 检查是否原路返还
            if($config['config']['refund_switch'] == 'Y')
            {
                $refundType = 3;
                $wanlpay = controller('addons\wanlshop\library\WanlPay\WanlPay')->packagerefund($row['id'], $row['price'],$row['order_id']);
                // code=0同步方法：refund判断fund_change = Y，代表退款成功，支付宝文档《如何判断退款是否成功》，https://opendocs.alipay.com/support/01rawa
                if(!empty($wanlpay) && $wanlpay['code'] == 0)
                {
                    // 退款中
                    $data['state'] = 4;
                    $refundLog = $wanlpay['data']['type_text'].'已将退款￥'.$wanlpay['data']['money'].'元原路返还买家'.$wanlpay['data']['type_text'].'账户';
                    // 如果退款成功,修改退款状态为第三方退款中，等待回调,否则退款到余额
                }else if(!empty($wanlpay) && $wanlpay['code'] == 200){
                    // 退款中
                    $data['state'] = 7;
                    $state = $data['state'];
                    // 退款日志
                    $refundLog = '已提交'.$wanlpay['data']['type_text'].'处理，预计24小时内将退款￥'.$wanlpay['data']['money'].'元原路返还买家'.$wanlpay['data']['type_text'].'账户';
                }
            }
            // 写入日志
            $this->refundLog($row['user_id'], $ids, $refundLog, $refundType);
            // 推送开始
            // 更新退款
            $result = $row->allowField(true)->save([
                'state' => $state,
                'completetime' => time()
            ]);
            //后续版本推送订购单
            // ...
            Db::commit();
        } catch (ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result !== false) {
            //stop cash in
            $monmonarr = \app\common\model\MoneyLogmonth::where(['deviceid'=>$order['deviceid'],'status'=>1])->where('month','GT',date('Ym'))->select();
            if($monmonarr){
                foreach($monmonarr as $valn){
                    \app\common\model\MoneyLogmonth::where('id',$valn['id'])->update(['status'=>0]);
                }
            }
            $scomonarr = \app\common\model\ScoreLogmonth::where(['deviceid'=>$order['deviceid'],'status'=>1])->where('month','GT',date('Ym'))->select();
            if($scomonarr){
                foreach($scomonarr as $vals){
                    \app\common\model\ScoreLogmonth::where('id',$vals['id'])->update(['status'=>0]);
                }
            }
            $this->success();
        } else {
            $this->error(__('No rows were updated'));
        }
    }

    /**
     * 拒绝退款
     */
    public function refuse($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($row['state'] != 0) {
            $this->error(__('当前状态，不可操作'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $result = false;
                Db::startTrans();
                try {
                    $params['state'] = 2;
                    // 写入日志
                    $this->refundLog($row['user_id'], $row['id'], '平台拒绝了您的退款申请，拒绝理由：'.$params['refuse_content']);
                    // 更新商品状态
                    $this->setOrderState(5,  $row['order_id']);
                    // 更新退款
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }



    /**
     * 更新订单商品状态（方法内使用）
     *
     * @ApiSummary  (WanlShop 更新订单商品状态)
     * @ApiMethod   (POST)
     *
     * @param string $status 状态
     * @param string $goods_id 商品ID
     */
    private function setOrderState($status = 0, $id = 0)
    {
        $orderGoodsModel = model('\app\admin\model\package\Order');
        return $orderGoodsModel->save(['refund_status' => $status],['id' => $id]);
    }


    /**
     * 修改订单状态（方法内使用） 1.0.5升级
     *
     * @ApiSummary  (WanlShop 修改订单状态)
     * @ApiMethod   (POST)
     *
     * @param string $id 订单ID
     */
    private function setRefundState($order_id = 0, $order_type = 'goods')
    {
        if($order_type === 'groups'){
            $orderModel = model('app\index\model\wanlshop\groups\Order');
            $orderGoodsModel = model('app\index\model\wanlshop\groups\OrderGoods');
        }else{
            $orderModel = model('app\index\model\wanlshop\Order');
            $orderGoodsModel = model('app\index\model\wanlshop\OrderGoods');
        }
        $list = $orderGoodsModel
            ->where(['order_id' => $order_id])
            ->select();
        $refundStatusCount = 0;
        foreach($list as $row){
            if($row['refund_status'] == 3) $refundStatusCount += 1;
        }
        // 如果订单下所有商品全部退款完毕则关闭订单
        if(count($list) == $refundStatusCount){
            $orderModel->save(['state'  => 7],['id' => $order_id]);
            return true;
        }
        return false;
    }

    /**
     * 退款日志（方法内使用）
     *
     * @ApiSummary  (WanlShop 退款日志)
     *
     * @param string $user_id 用户ID
     * @param string $refund_id 退款ID
     * @param string $content 日志内容
     * @param string $type 退款状态:0=买家,1=卖家,2=官方,3=系统
     */
    private function refundLog($user_id = 0, $refund_id = 0, $content = '', $type = 1)
    {
        return model('\app\admin\model\WatchPackageRefundLog')->allowField(true)->save([
            'user_id' => $user_id,
            'refund_id' => $refund_id,
            'type' => $type,
            'content' => $content
        ]);
    }

}
